package com.hhp.cloud.shop.auth.security.core.userdetails.user;

import cn.hutool.core.lang.TypeReference;
import com.hhp.cloud.shop.auth.feign.UserFeignService;
import com.hhp.cloud.shop.auth.vo.UserAuthVo;
import com.hhp.cloud.shop.common.core.enums.BizCodeEnume;
import com.hhp.cloud.shop.common.core.result.R;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @Description: 系统用户体系业务类
 * @author: hhp
 * @date: 2021/11/23 16:54
 */
@Service("sysUserDetailsService")
@Slf4j
/**
 * @RequiredArgsConstructor 使用这个注解 UserFeignService会注册不进去
 * 可在application启动类里@EnableFeignClients(basePackageClasses = {UserFeignClient.class, MemberFeignClient.class})
 * @RequiredArgsConstructor 需要加final
 */
//@AllArgsConstructor
@RequiredArgsConstructor
public class SysUserDetailsServiceImpl implements UserDetailsService {

    private final UserFeignService userFeignService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUserDetails userDetails = null;
        R<UserAuthVo> result = userFeignService.getUserByUsername(username);
        if (R.ok().getCode() == result.getCode()) {
            UserAuthVo user = result.getData(new TypeReference<UserAuthVo>() {});
            if (null != user) {
                userDetails = new SysUserDetails(user);
            }
        }
        if (userDetails == null) {
            throw new UsernameNotFoundException(BizCodeEnume.USER_NOT_EXIST.getMsg());
        } else if (!userDetails.isEnabled()) {
            throw new DisabledException("该账户已被禁用!");
        } else if (!userDetails.isAccountNonLocked()) {
            throw new LockedException("该账号已被锁定!");
        } else if (!userDetails.isAccountNonExpired()) {
            throw new AccountExpiredException("该账号已过期!");
        }
        return userDetails;
    }

}
